package org.otherworld.frame.filebrowser.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.TreePath;

import org.otherworld.frame.filebrowser.FilePanel;
import org.otherworld.frame.filebrowser.tree.FileTreeNode;

public class FileBrowserCopy implements ActionListener {

	private File selectFile;
	private File editFile;
	private JPanel panel;
	private File selectPath = null;
	private File editPath = null;
	private JTree tree;
	
	public FileBrowserCopy(JPanel panel,JTree tree) {
		this.panel = panel;
		this.tree = tree;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		JTree selected = tree;
		String name = selected.getName();
		Component[] comps = panel.getComponents();

		String otherName = null;
		if (name.equals("left")) {
			otherName = "right";
		} else {
			otherName = "left";
		}
		JTree other = this.getOtherTree(comps, name);

		TreePath[] paths = selected.getSelectionPaths();
		TreePath otherPath = other.getSelectionPath();

		if (paths != null) {
			for (int i = 0; i < paths.length; i++) {
				FileTreeNode node = (FileTreeNode) paths[i]
						.getLastPathComponent();
				this.editPath = node.getFile();
				System.out.println(name + " path: " + node.getFile());
			}
		} else {
			System.out.println("Path null");
		}

		if (otherPath != null) {
			FileTreeNode node = (FileTreeNode) otherPath
					.getLastPathComponent();
			this.selectPath = node.getFile();
			System.out.println(otherName + " path: " + node.getFile());
		} else {
			System.out.println("Other path null");
		}
		
		System.out.println(editPath + " - "+selectPath);
		File sourceFile = editPath;
		File targetFile = new File(selectPath+editPath.getName());
		
		if (sourceFile != null) {
			try {
				InputStream in = new FileInputStream(sourceFile);
				OutputStream out = new FileOutputStream(targetFile);
				int length;
				byte[] buffer = new byte[1024];
				while ((length = in.read(buffer)) > 0) {
					out.write(buffer, 0, length);
				}
				in.close();
				out.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}
	
	private JTree getOtherTree(Component[] comps, String fireName) {
		Object temp = null;
		for (int i = 0; i < comps.length; i++) {
			temp = comps[i];
			if (temp instanceof FilePanel) {
				temp = (FilePanel) comps[i];
				if (fireName != ((FilePanel) temp).getTree().getName()) {
					return ((FilePanel) temp).getTree();
				}
			}
		}
		return null;
	}

}
